package com.pvdnc.worldmagisk.shell.client;

import android.util.Log;

import com.pvdnc.worldmagisk.shell.Packet;
import com.pvdnc.worldmagisk.shell.PacketDecoder;
import com.pvdnc.worldmagisk.shell.PacketEncoder;

import java.net.InetAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class ShellClient {
    private static final String TAG=ShellClient.class.getSimpleName();

    private int mPort;
    public ShellClient(int port){
        mPort=port;
    }

    public Bootstrap getDefault(){
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap
                .group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    public void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast(new PacketDecoder());
                        ch.pipeline().addLast(new CommandResponseHandler() {
                            @Override
                            public void onResult(String result) {
                                Log.d(TAG,"command result:\n\t"+result);
                            }
                        });
                        ch.pipeline().addLast(new PacketEncoder());
                    }
                });
        return bootstrap;
    }

    private Channel mChannel;

    public void doConnect(){
        getDefault().connect("localhost",mPort).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Log.d(TAG,"connected to shell server");
                mChannel=future.channel();
                sendCommand("id");
                Log.d(TAG,"id demo sent");
            }
        });
    }

    public void sendCommand(String cmd){
        Packet packet=new Packet();
        packet.mType=Packet.TYPE_REQUEST;
        packet.mData=cmd.getBytes();
        mChannel.writeAndFlush(packet);
    }
}
